package net.bwie.realtime.jtp.dwd.log.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.bwie.realtime.jtp.utils.DateTimeUtil;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class AdjustIsNewProcessFunction extends KeyedProcessFunction<String,String,String> {
    //声明状态
    private transient ValueState<String> firstDateState = null;


    @Override
    public void open(Configuration parameters) throws Exception {
        //初始化状态
        firstDateState = getRuntimeContext().getState(
                new ValueStateDescriptor<String>("first-date", String.class)
        );
    }

    @Override
    public void processElement(String s,Context context, Collector<String> collector) throws Exception {
        //获取状态值
        String firstDate = firstDateState.value();
        //解析字段值
        JSONObject jsonObject = JSON.parseObject(s);
        String isNewValue = jsonObject.getJSONObject("common").getString("is_new");
        Long tsValue = jsonObject.getLong("ts");
        //字段值为1时
        if("1".equals(isNewValue)){
            //状态值为NULL时
            if(null == firstDate){
                //更新状态值
                //此时is_new正确,状态值更新为第一次访问的日期
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue,DateTimeUtil.DATE_FORMAT));
            }else {
                //状态值(首次访问日期)等于数据日期,不做处理
                if(!firstDate.equals(DateTimeUtil.convertLongToString(tsValue,DateTimeUtil.DATE_FORMAT))){
                    //需要纠正is_new字段
                    jsonObject.getJSONObject("common").put("is_new","0");
                }
            }
        }else{
            //如果该用户第一次为0
            if(null == firstDate){
                //设置一个昨天日期即可
                firstDateState.update(DateTimeUtil.convertLongToString(tsValue-86400000,DateTimeUtil.DATE_FORMAT));
            }
        }
        collector.collect(jsonObject.toJSONString());
    }
}